import CryptoJS from 'crypto-js'
import JSEncrypt from 'jsencrypt'
import JsRsaSign from 'jsrsasign'

/**
 * RSA 加密
 * @param publicKey   公钥
 * @param plainText   明文
 * @returns {string | false}
 */
export function encryptByRSA(publicKey, plainText) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey)
  return encryptor.encrypt(plainText)
}

/**
 * RSA 解密
 * @param privateKey 私钥
 * @param cipherText 密文
 */
export function decryptByRSA(privateKey, cipherText) {
  const decryptor = new JSEncrypt()
  decryptor.setPrivateKey(privateKey)
  return decryptor.decrypt(cipherText)
}

/**
 * 生成RSA密钥对，填充模式为PKCS8
 * @returns {{privateKey: (string|string|*), publicKey: (string|string|*)}}
 */
export function generateRsaKeyWithPKCS8() {
  const keyPair = JsRsaSign.KEYUTIL.generateKeypair('RSA', 1024)
  const privateKey = JsRsaSign.KEYUTIL.getPEM(keyPair.prvKeyObj, 'PKCS8PRV')
  const publicKey = JsRsaSign.KEYUTIL.getPEM(keyPair.pubKeyObj)
  return { privateKey, publicKey }
}

/**
 * SHA256和RSA加签
 * @param privateKey 私钥
 * @param msg  加签名的内容
 * @returns {string} Base64编码签名内容
 */
export function signBySHA256WithRSA(privateKey, msg) {
  const key = JsRsaSign.KEYUTIL.getKey(privateKey)
  const signature = new JsRsaSign.KJUR.crypto.Signature({
    alg: 'SHA256withRSA'
  })
  signature.init(key)
  signature.updateString(msg)
  return JsRsaSign.hextob64(signature.sign())
}

export function verifyBySHA256WithRSA(publicKey, base64SignStr, msg) {
  const key = JsRsaSign.KEYUTIL.getKey(publicKey)
  const signature = new JsRsaSign.KJUR.crypto.Signature({
    alg: 'SHA256withRSA'
  })
  signature.init(key)
  signature.updateString(msg)
  return signature.verify(JsRsaSign.b64tohex(base64SignStr))
}
